import {
  getOrderInfo,
  getOrderAddress,
  getOrderBuy,
  submitOrder,
  createJsapi,
  queryPayStatus,
} from "@/api/orderpay";
import { formatTime } from "@/utils/formatTime";
Page({
  data: {
    buyName: "", // 订购人姓名
    buyPhone: "", // 订购人手机号
    deliveryDate: "选择送达日期", // 期望送达日期
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    orderAddress: {}, // 订单地址
    orderInfo: {}, // 订单详情
    remarks: "", // // 祝福语
    goodsId: "",
    flag: 0, // 更新收货地址，如果是1则说明从地址列表中返回回来
    orderNo: "", // 订单号
  },

  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true,
    });
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const timeRes = formatTime(new Date(event.detail));
    this.setData({
      show: false,
      deliveryDate: timeRes,
    });
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime(),
    });
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/list/index`,
    });
  },

  // 订单详情
  async getOrderInfo() {
    // 需要区分是从 立即购买 来的还是 购物车的去结算来的，分别调用不同的接口
    const { data } = this.data.goodsId
      ? await getOrderBuy({
          goodsId: this.data.goodsId,
          blessing: this.data.remarks,
        })
      : await getOrderInfo();
    console.log("订单详情=》", data);
    if (data.code === 200) {
      this.setData({
        orderInfo: data.data,
        remarks: this.data.goodsId
          ? this.data.remarks
          : data.data.cartVoList.find((item, index) => item.blessing !== "")
              ?.blessing,
      });
    }
  },

  // 订单地址
  async getOrderAddress() {
    const { data } = await getOrderAddress();
    console.log("订单地址=》", data);
    if (data.code === 200) {
      this.setData({
        orderAddress: data.data,
      });
    }
  },

  // 提交订单
  async submitOrder() {
    const params = {};
    params.buyName = this.data.buyName;
    params.buyPhone = this.data.buyPhone;
    params.cartList = this.data.orderInfo.cartVoList;
    params.deliveryDate = formatTime(new Date()); // 下单时间
    params.remarks = this.data.remarks;
    params.userAddressId = this.data.orderAddress.id;
    const { data } = await submitOrder(params);
    // console.log("提交订单=》", data);
    if (data.code === 200) {
      this.data.orderNo = data.data;
      this.createJsapi();
    }
  },

  // 微信预支付信息
  async createJsapi() {
    const { data } = await createJsapi({ orderNo: this.data.orderNo });
    console.log("微信预支付信息=》", data);
    if (data.code === 200) {
      // 唤起微信支付组件，完成支付
      wx.requestPayment({
        timeStamp: data.data.timeStamp,
        nonceStr: data.data.nonceStr,
        package: data.data.package,
        paySign: data.data.paySign,
        signType: data.data.signType,
        async success(res) {
          // 支付成功回调，实现自定义的业务逻辑
          if (res.errMsg === "requestPayment:ok") {
            // 查询支付的状态
            const { data } = await queryPayStatus({
              orderNo: this.data.orderNo,
            });
            if (data.code === 200) {
              wx.redirectTo({
                url: "/modules/orderPayModule/pages/order/list/list",
                success: function (res) {
                  wx.showToast({ title: "支付成功", icon: "success" });
                },
                fail: function () {
                  wx.showToast({ title: "支付失败", icon: "success" });
                },
              });
            }
          }
        },
        fail(err) {
          // 支付失败回调
          console.log("支付失败=》", err);
          wx.showToast({ title: "支付失败，请联系客服", icon: "error" });
        },
      });
    }
  },

  onLoad(options) {
    console.log("接收的参数=》", options);
    if (options) {
      if (options.goodsId) {
        wx.setStorageSync("goodsId", options.goodsId);
      } else if (!options.flag) {
        wx.removeStorageSync("goodsId");
      }
      if (options.blessing) {
        wx.setStorageSync("remarks", options.blessing);
      } else if (!options.flag) {
        wx.removeStorageSync("remarks");
      }
      this.setData({
        orderAddress: options.addressItem
          ? JSON.parse(options.addressItem)
          : {},
        goodsId: wx.getStorageSync("goodsId") || "",
        remarks: wx.getStorageSync("remarks") || "",
        flag: options.flag || 0,
      });
    }
  },

  onShow() {
    if (Object.keys(this.data.orderAddress).length === 0) {
      this.getOrderAddress();
    }

    this.getOrderInfo();
  },
});
